﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Web.UI;
using System.Web.Security;
using System.Security.Cryptography;

namespace Common
{
    public class Utility
    {

        /// <summary>
        /// 判断是否为整形
        /// </summary>
        /// <param name="chkint_str">需要判断的对象</param>
        /// <returns>如果是整形返回True，如果不是返回False</returns>
        public static bool chk_int(object chkint_str)
        {
            try
            {
                int tempint = Convert.ToInt32(chkint_str);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary> 
        /// 获取计时器事件运行的时间间隔 
        /// </summary> 
        /// <returns>时间间隔</returns> 
        public static double GetTimerInterval(DateTime dt1,DateTime dt2)
        {
            DateTime runTime = Convert.ToDateTime(System.Configuration.ConfigurationSettings.AppSettings["TimerRunAt"]);
            //运行时间 
            TimeSpan ts = dt2.Subtract(dt1);
            return ts.TotalMinutes;
        }

        /// <summary>
        /// 创建MD5
        /// </summary>
        /// <param name="str">要创建的MD5字符串</param>
        /// <returns>返回MD5加密字符串</returns>
        public static string MD5(string str)
        {
            byte[] b = Encoding.Default.GetBytes(str);
            b = new MD5CryptoServiceProvider().ComputeHash(b);
            string ret = "";
            for (int i = 0; i < b.Length; i++)
                ret += b[i].ToString("x").PadLeft(2, '0');
            return ret;
        }

        public static bool IsExistObjectProperty(object obj, string propertyname)
        {
            return GetObjectPropertyInfo(obj, propertyname) != null;
        }

        public static PropertyInfo GetObjectPropertyInfo(object obj, string propertyname)
        {
            return obj.GetType().GetProperty(propertyname); ;
        }

        public static object GetObjectValue(object obj, string propertyname)
        {
            if (IsExistObjectProperty(obj, propertyname))
            {
                return GetObjectPropertyInfo(obj, propertyname).GetValue(obj, null);
            }
            else
                throw new Exception(string.Format("对象{0}不存在属性：{1}", obj.ToString(), propertyname));
        }

        public static void SetObjectValue(object obj, string propertyname, object v)
        {
            if (IsExistObjectProperty(obj, propertyname))
            {
                GetObjectPropertyInfo(obj, propertyname).SetValue(obj, v, null);
            }
            else
                throw new Exception(string.Format("对象{0}不存在属性：{1}", obj.ToString(), propertyname));
        }
        public static void SetObjectValueWithTheSamePropertyName(object obj, object anotherobj)
        {
            Type type = obj.GetType();
            PropertyInfo[] pi = type.GetProperties();

            PropertyInfo[] anotherobjpi = anotherobj.GetType().GetProperties();

            for (int i = 0; i < pi.Length; i++)
            {
                for (int j = 0; j < anotherobjpi.Length; j++)
                {
                    Type piPropertyType = pi[i].PropertyType;

                    if (pi[i].Name == anotherobjpi[j].Name
                        && (!pi[i].PropertyType.IsGenericType ||
                            piPropertyType == typeof(DateTime?) ||
                            piPropertyType == typeof(Boolean?) ||
                            piPropertyType == typeof(int?) ||
                            piPropertyType == typeof(Guid?) ||
                            piPropertyType == typeof(byte?)||
                            piPropertyType == typeof(decimal?)
                            )
                        && pi[i].PropertyType != typeof(IList)
                        && (!pi[i].PropertyType.IsClass || pi[i].PropertyType == typeof(string)))
                    {
                        object anotherobjpivalue = anotherobjpi[j].GetValue(anotherobj, null);

                        if (pi[i].Name.ToLower() == "id" && anotherobjpivalue.ToString() == "0")
                            break;

                        //if (anotherobjpi[j].PropertyType == typeof(int) && anotherobjpivalue.ToString() == "0")
                        //    break;

                        if (anotherobjpi[j].PropertyType == typeof(DateTime) && anotherobjpivalue.ToString() == "0001-1-1 0:00:00")
                            break;

                        bool isNullType = false;
                        if (piPropertyType == typeof(int?))
                        {
                            piPropertyType = typeof(int);
                            isNullType = true;
                        }
                        if (piPropertyType == typeof(DateTime?))
                        {
                            piPropertyType = typeof(DateTime);
                            isNullType = true;
                        }
                        if (piPropertyType == typeof(Boolean?))
                        {
                            piPropertyType = typeof(Boolean);
                            isNullType = true;
                        }
                        if (piPropertyType == typeof(Guid?))
                        {
                            piPropertyType = typeof(Guid);
                            isNullType = true;
                        }
                        if (piPropertyType == typeof(byte?))
                        {
                            piPropertyType = typeof(byte);
                            isNullType = true;
                        }
                        if (piPropertyType == typeof(decimal?))
                        {
                            piPropertyType = typeof(decimal);
                            isNullType = true;
                        }
                        if (!isNullType)
                        {
                            if (anotherobjpivalue != null &&
                                (anotherobjpivalue ?? string.Empty).ToString().Trim() != (GetObjectValue(obj, pi[i].Name) ?? string.Empty).ToString().Trim())
                                pi[i].SetValue(obj, Convert.ChangeType(anotherobjpivalue, piPropertyType), null);
                        }
                        else
                        {
                            if (anotherobjpivalue == null)
                                pi[i].SetValue(obj, null, null);
                            else
                            {
                                pi[i].SetValue(obj, Convert.ChangeType(anotherobjpivalue, piPropertyType), null);
                            }
                        }
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 显示JavaScript
        /// </summary>
        /// <param name="StrJs">希望显示的JavaScript</param>
        /// <param name="e">Page</param>
        public static void ShowJs(String StrJs, Page e)
        {
            String strJScript = "<Script Language='JavaScript'>\n" + "<!--\n" + StrJs + "\n" + "//-->\n" + "</Script>";
            //e.RegisterClientScriptBlock("script", strJScript);
            e.ClientScript.RegisterClientScriptBlock(e.GetType(), "script1", strJScript);
        }

        /// <summary>
        /// 刷新父级页面
        /// <param name="e">Page</param>
        /// </summary>
        static public void ReloadTopPage(Page e)
        {
            String strJScript = "window.parent.location.reload();";
            ShowJs(strJScript, e);
        }
        static public void ReloadParentPage(Page e)
        {
            String strJScript = " window.opener.location.reload();";
            ShowJs(strJScript, e);
        }

        /// <summary>
        /// 显示JavaScript Alert
        /// </summary>
        /// <param name="strAlert">显示Alert内容</param>
        /// <param name="e">Page</param>
        static public void ShowJsAlertAndHistoryBack(String strAlert, Page e)
        {
            String strJScript = "alert('" + strAlert + "');" + "history.back();";
            //String strJScript = "Boxy.alert('" + strAlert + "');" + "history.back();";
            ShowJs(strJScript, e);
        }

        /// <summary>
        /// 显示JavaScript Alert
        /// </summary>
        /// <param name="strAlert">显示Alert内容</param>
        /// <param name="e">Page</param>
        static public void ShowJsAlert(String strAlert, Page e)
        {
            String strJScript = string.Format("alert('{0}');", strAlert);
            //String strJScript = string.Format("Boxy.alert('{0}');", strAlert);
            ShowJs(strJScript, e);
        }

        /// <summary>
        /// 显示JavaScript Alert 并关闭当前窗口
        /// </summary>
        /// <param name="strAlert">显示Alert内容</param>
        /// <param name="e">Page</param>
        public static void ShowJsAlertAndClose(String strAlert, Page e)
        {
            String strJScript = "alert('" + strAlert + "');" + "close();";
            ShowJs(strJScript, e);
        }

        /// <summary>
        /// 显示JavaScript Alert 并跳转到新页面
        /// </summary>
        /// <param name="strURL">跳转URL</param>
        /// <param name="strAlert">显示Alert内容</param>
        /// <param name="e">Page</param>
        public static void ShowJsAlertAndRefresh(String strURL, String strAlert, Page e)
        {
            String strJScript = "alert('" + strAlert + "');" + "document.location='" + strURL + "'";
            ShowJs(strJScript, e);
        }

        /// <summary>
        /// 显示JavaScript Alert 并关闭当前窗口,且刷新父窗口
        /// </summary>
        /// <param name="strURL">跳转URL</param>
        /// <param name="strAlert">显示Alert内容</param>
        /// <param name="e">Page</param>
        public static void ShowJsAlertAndCloseRefresh(String strURL, String strAlert, Page e)
        {
            String strJScript = "alert('" + strAlert + "');" + "close();window.opener.location='" + strURL + "'";
            ShowJs(strJScript, e);
        }

        /// <summary>
        /// 显示JavaScript Alert 并关闭当前窗口,且刷新父窗口
        /// </summary>
        /// <param name="strAlert">显示Alert内容</param>
        /// <param name="e">Page</param>
        public static void ShowJsAlertAndCloseRefresh(String strAlert, Page e)
        {
            String strJScript = "alert('" + strAlert + "');" + "close();window.parent.location.reload();";
            ShowJs(strJScript, e);
        }

        public static void GoUrl(string Strurl, Page e)
        {
            String strJScript = "window.parent.location=" + Strurl + ";";
            ShowJs(strJScript, e);
        }

        /// <summary>
        /// 显示JavaScript Alert 并跳转到其他窗口
        /// </summary>
        /// <param name="strURL">跳转URL</param>
        /// <param name="strAlert">显示Alert内容</param>
        /// <param name="e">Page</param>
        public static void ShowJsAlertAndRedirect(String strURL, String strAlert, Page e)
        {
            String strJScript = "alert('" + strAlert + "');" + "location='" + strURL + "'";
            ShowJs(strJScript, e);
        }

        /// <summary>
        /// 显示一个Boxy Alert
        /// </summary>
        /// <param name="t">标题</param>
        /// <param name="u">跳转地址</param>
        static public void ShowBoxyConfirm(string t,string u,Page e)
        {
            String strJScript = "Boxy.confirm('" + t + "',function(){document.location='" + u + "';});";
            ShowJs("$(document).ready(function(){" + strJScript + "})", e);
        }

        /// <summary>
        /// 显示Boxy Alert
        /// </summary>
        /// <param name="strAlert">显示Alert内容</param>
        /// <param name="e">Page</param>
        static public void ShowBoxyAlertAndHistoryBack(String strAlert, Page e)
        {
            //String strJScript = "alert('" + strAlert + "');" + "history.back();";
            String strJScript = "Boxy.alert('" + strAlert + "');" + "history.back();";
            ShowJs("$(document).ready(function(){" + strJScript + "})", e);
        }

        /// <summary>
        /// 显示Boxy Alert
        /// </summary>
        /// <param name="strAlert">显示Alert内容</param>
        /// <param name="e">Page</param>
        static public void ShowBoxyAlert(String strAlert, Page e)
        {
            //String strJScript = string.Format("alert('{0}');", strAlert);
            String strJScript = string.Format("Boxy.alert('{0}');", strAlert);
            ShowJs("$(document).ready(function(){" + strJScript + "})", e);
        }

        /// <summary>
        /// 生成一个随机数
        /// </summary>
        /// <param name="small">最小值</param>
        /// <param name="max">最大值</param>
        /// <returns></returns>
        public static int GetRandom(int small, int max)
        {
            long tick = DateTime.Now.Ticks;
            Random r = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
            return r.Next(small, max + 1);
        }

        public static string RandomColor()
        {
            string[] arrHex = new string[] { "4a3113","5c7a29","87481f","4e72b8","543044","008080", "0000ff", "ff00ff", "808080", "008000", "808080", "00ff00", "800000", "000080", "808000", "ffa500", "800080", "ff0000", "c0c0c0", "008080", "ffcc00" };
            string strHex = "#";
            int index = GetRandom(0, 20);
            strHex += arrHex[index];
            return strHex;
        }

        public static string AscToChr(int asciiCode)
        {
            if (asciiCode >= 0 && asciiCode <= 255)
            {
                System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
                byte[] byteArray = new byte[] { (byte)asciiCode };
                string strCharacter = asciiEncoding.GetString(byteArray);
                return (strCharacter);
            }
            else
            {
                return "";
            }
        }
    }
}
